module Api
  class CaptchaController < ApplicationController
    skip_before_action :verify_authenticity_token

    def new
      if /^((\(\d{3}\))|(\d{3}\-))?1[3-9][0-9]\d{8}|15[89]\d{8}/.match(params[:mobile])
        captcha = create_stored_captcha

        if send_sms(params[:mobile], captcha)
          data!
        else
          error! "发送失败"
        end
      else
        error! "手机号不正确"
      end
    end

    private
      def create_stored_captcha
        captcha = [*0..9].sample(6).join
        redis_set("sms_captcha:#{params[:mobile]}",
                  captcha,
                  ex: CAPTCHA_EXPIRE_TIME)
        captcha
      end

      def send_sms(mobile, captcha)
        sms = "“#{APP_NAME}”手机app验证码：#{captcha}。"
        url = "http://#{ENV["SMS_SERVER"]}/cgi-bin/sendsms?username=#{ENV["SMS_USERNAME"]}&password=#{ENV["SMS_PASSWORD"]}&to=#{mobile}&text=#{URI::encode sms.encode('GB2312')}&msgtype=1"
        ret_str = Net::HTTP.get(URI(url))
        ret_str == '0'
      end
  end
end